/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useEffect, useRef, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useLocation } from "react-router-dom";
import ListHead from "../../components/ListHead/listHead";
import MusicList from "../../components/MusicList/musicList";
import Player from "../../components/MusicFooter/musicFooter";
import { RootState, AppDispatch } from "../../store";
import { updatedMusicId } from "../../store/musicSlice";
import { addMusicList } from '../../utils/common';
import { allMusiclist } from "../../store/musicSlice";
import "./index.less";

const MusicListView: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const location = useLocation();

  // Redux state
  const musicListNum = useSelector((state: RootState) => state.music.musicListNum);
  const musicList = useSelector((state: RootState) => state.music.musicList);

  // 本地 state
  const [isShowMenu, setIsShowMenu] = useState(false);
  const [musicId, setMusicId] = useState(1);
  const [oneMusic, setOneMusic] = useState<any>({});
  const [updataMusic, setUpdataMusic] = useState<any>({});
  const [deviceType, setDeviceType] = useState("mobile");
  const childElement = useRef<any>(null);

  // 解析 query 参数
  const getQuery = () => {
    const search = location.search;
    const params = new URLSearchParams(search);
    return {
      musicId: params.get("musicId"),
      isPlay: params.get("isPlay"),
    };
  };

  useEffect(() => {
    if(musicList && musicList.length === 0){
      const MusicListCache = sessionStorage.getItem("musicList");
      if (MusicListCache) {
        dispatch(allMusiclist(JSON.parse(MusicListCache)));
      }else{
        const musicList = addMusicList(musicListNum);
        dispatch(allMusiclist(musicList));
      }
  
    }
     // 监听点击事件
     const handleClick = (event: MouseEvent) => {
      if (event.target !== childElement.current) {
        setIsShowMenu(false);
      }
    };
    document.addEventListener("click", handleClick);


    // 监听触摸移动事件
    const handleTouchMove = (e: TouchEvent) => {
      const el = document.querySelector('.musicList') as HTMLElement;
      const scrollTop = el.scrollTop;
      const scrollHeight = el.scrollHeight;
      const offsetHeight = el.offsetHeight;
      const isAtTop = scrollTop === 0;
      const isAtBottom = scrollTop + offsetHeight >= scrollHeight;
  
      // 检查触摸点的垂直位移
      const verticalDelta = Math.abs(e.touches[0].clientY - (e.touches[0].clientY - e.touches[0].clientY));
      const horizontalDelta = Math.abs(e.touches[0].clientX - (e.touches[0].clientX - e.touches[0].clientX));
  
      // 如果主要是垂直滑动且在顶部或底部，禁止默认行为
      if ((isAtTop && e.touches[0].clientY > 0) || (isAtBottom && e.touches[0].clientY < 0)) {
        if (verticalDelta > horizontalDelta) {
          e.preventDefault();
        }
      }
    };
    const el = document.querySelector('.musicList') as HTMLElement;
    el.addEventListener('touchmove', handleTouchMove, { passive: false });
  

    // 监听窗口大小
    const handleResize = () => {
      setDeviceType(window.innerWidth > 500 ? "pc" : "mobile");
    };
    setDeviceType(window.innerWidth > 500 ? "pc" : "mobile");
    window.addEventListener("resize", handleResize);

    return () => {
      document.removeEventListener("click", handleClick);
      window.removeEventListener("resize", handleResize);
      el.removeEventListener('touchmove', handleTouchMove, { passive: false } as any);
    };
  }, []);

  useEffect(() => {
    // 初始化 musicId 和 oneMusic
    const query = getQuery();
    if (query.musicId) {
      setOneMusic(musicList[Number(query.musicId) - 1]);
      setMusicId(Number(query.musicId));
    } else {
      setOneMusic(musicList[0]);
      setMusicId(1);
    }
   
    // eslint-disable-next-line
  }, [musicList]);

  // 处理子组件事件
  const handleMusic = (obj: any) => {
    setOneMusic(obj);
  };

  const getUpdataMusic = (obj: any) => {
    obj.getOneMusic();
    let oneMusicinner = musicList.filter(item => item.id === Number(obj.musicId))[0];
    setOneMusic(oneMusicinner);
    dispatch(updatedMusicId(oneMusicinner.id));
    setMusicId(oneMusicinner.id);
    setUpdataMusic(obj);
  };

  const query = getQuery();

  return (
    <div className="musicList">
      <ListHead deviceType={deviceType} listNum={musicListNum} />
      <div className="content">
        <MusicList
          listNum={musicListNum}
          deviceType={deviceType}
          updataMusic={updataMusic}
        />
      </div>
      <div className="footer">
        <Player
          oneMusic={oneMusic}
          listNum={musicListNum}
          deviceType={deviceType}
          musicId={musicId}
          isPlay={query.isPlay === 'play' ? query.isPlay : 'pause'}
          onUpdateMusic={getUpdataMusic}
        />
      </div>
    </div>
  );
};

export default MusicListView;